//
//  WDPersonalSettingViewController.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/8/17.
//

#import "WDPersonalSettingViewController.h"
#import "WDPersonalSettingViewModel.h"
#import "WDPersonalSettingHeaderCell.h"
#import "WDPersonalSettingViewCell.h"
#import "WDCancelWorkOrderBottomView.h"
#import "WDPersonalInfoModifyTipView.h"
#import "EDSCustomDatePicker.h"
#import "WDPersonalSettingTopView.h"
#import "WDPersonalSettingNewViewCell.h"
#import "AuthorityManager.h"


@interface WDPersonalSettingViewController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) WDPersonalSettingViewModel *viewModel;

@property (nonatomic, strong) WDPersonalSettingTopView *topView;


@property (nonatomic, strong) WDCancelWorkOrderBottomView *bottomView;

@property (nonatomic, strong) WDPersonalInfoModifyTipView *modifyTipView;

/// 日期选择
@property (nonatomic, strong) EDSCustomDatePicker *datePicker;

@end

@implementation WDPersonalSettingViewController

- (void)dealloc {
    debugMethod();
    
}

- (void)initWithVar {
    [super initWithVar];
    
}

- (void)initWithViewModel {
    _viewModel = [WDPersonalSettingViewModel new];
    
}

- (void)initWithNavBar {
    [super initWithNavBar];
    
    [self initWithBackButton];
    
    self.navigationItem.title = self.viewModel.title;
}

- (void)initWithSubView {
    [super initWithSubView];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.baseTableView.backgroundColor = [UIColor whiteColor];
    self.baseTableView.height = self.baseTableView.height - TABBAR_HEIGHT;
    [self.baseTableView registerClass:[WDPersonalSettingHeaderCell class] forCellReuseIdentifier:[WDPersonalSettingHeaderCell className]];
    
    [self.baseTableView registerClass:[WDPersonalSettingViewCell class] forCellReuseIdentifier:[WDPersonalSettingViewCell className]];
    [self.baseTableView registerClass:[WDPersonalSettingNewViewCell class] forCellReuseIdentifier:[WDPersonalSettingNewViewCell className]];
    
    self.baseTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self initWithBottomView];
    
    [self initWithModifyTipView];
    
    [self initWithDatePicker];
}

- (void)initWithHeaderView {
    if (!_topView) {
        CGRect frame = CGRectMake(0, 0, kScreenW, kWDPersonalSettingTopViewHeight);
        _topView = [[WDPersonalSettingTopView alloc] initWithFrame:frame];
        self.baseTableView.tableHeaderView = self.topView;
        @weakify(self);
        _topView.touchHeaderBlock = ^{
            @strongify(self);
            [self actionWithUpdateHeaderImage];
        };
    }
    [self.topView updateWithViewData:self.viewModel];
}

- (void)initWithBottomView {
    CGRect frame = CGRectMake(0, self.baseTableView.bottom, kScreenW, TABBAR_HEIGHT);
    _bottomView = [[WDCancelWorkOrderBottomView alloc] initWithFrame:frame];
    _bottomView.btnTitle = @"确认修改";
    [self.view addSubview:_bottomView];
        @weakify(self);
    _bottomView.viewBlock = ^(id  _Nullable data) {
        @strongify(self);
        [self actionWithSubmit];
    };
}

- (void)initWithModifyTipView {
    CGRect frame = CGRectMake((kScreenW - 296) * 0.5, (kScreenH - 160) * 0.5 - 30, 296, 160);
    _modifyTipView = [[WDPersonalInfoModifyTipView alloc] initWithFrame:frame];
}

- (void)initWithDatePicker {
    CGRect frame = CGRectMake(0, kScreenH, kScreenW, kEDSCustomDatePickerHeight);
    _datePicker = [[EDSCustomDatePicker alloc] initWithFrame:frame autoSelected:NO isPeriodTime:0];
    _datePicker.topView.backgroundColor = kThemeColor;
    @weakify(self);
    _datePicker.touchDateBlock = ^(NSString * _Nonnull date) {
        @strongify(self);
        TYZCommonCellModel *model = [self.viewModel.dataList objectOrNilAtIndex:4];
        model.value = date;
        [self.baseTableView reloadData];
    };
}

/// 确认修改
- (void)actionWithSubmit {
    @weakify(self);
    
    // 姓名
    TYZCommonCellModel *model = [self.viewModel.dataList objectOrNilAtIndex:1];
    NSString *userName = objectNull(model.value);
    if ([userName isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入姓名！"];
        return;
    }
    if (userName.length > 20) {
        [SVProgressHUD showInfoWithStatus:@"姓名不能超过20个字！"];
        return;
    }
    
    // 手机号
    model = [self.viewModel.dataList objectOrNilAtIndex:2];
    NSString *phone = objectNull(model.value);
    if ([phone isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入手机号！"];
        return;
    }
    if (phone.length != 11) {
        [SVProgressHUD showInfoWithStatus:@"请输入11位手机号！"];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"修改中......"];
    [self.viewModel requestWithUserInfoUpdate:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            [self reloadUserInfo];
            [SVProgressHUD showSuccessWithStatus:@"修改成功！"];
            [self clickedBack:nil];
        } else {
//            [SVProgressHUD dismiss];
            NSString *tip = objectNull(respond.msg);
            if ([tip isEqualToString:@""]) {
                tip = @"修改失败，请稍后再试！";
            }
            [SVProgressHUD showInfoWithStatus:tip];
//            [self errorShowTip];
        }
    }];
}

/// 获取用户信息
- (void)reloadUserInfo {
    [[EDSAppDelegateTool sharedInstance] requestWithUserInfo:^(EDSRespondDataEntity * _Nonnull respond) {
            
    }];
}

/// 错误提示
- (void)errorShowTip {
    @weakify(self);
    NSDictionary *params = @{
        @"desc": @"显示返回的错误信息",
        @"imageTipName": @"ic-error-tip"
    };
    [_modifyTipView showWithTitle:@"修改失败" data:params completion:^{
        @strongify(self);
        [self.modifyTipView hide];
    } failed:^{
        @strongify(self);
        [self.modifyTipView hide];
    }];
}


/// 修改头像
- (void)actionWithUpdateHeaderImage {
    [self clickedAddImage];
}

/// 上传头像
/// - Parameter image: image description
- (void)actionWithUploadImage:(UIImage *)image {
    EDSImageVideoModel *model = [EDSImageVideoModel new];
    model.type = 0;
    model.srcImage = image;
    
    @weakify(self);
    [SVProgressHUD showWithStatus:@"上传中......"];
    [self.viewModel requestWithUploadImage:model completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            [SVProgressHUD showSuccessWithStatus:@"上传成功！"];
//            [self.baseTableView reloadData];
            [self initWithHeaderView];
        } else {
            [SVProgressHUD showInfoWithStatus:@"上传失败，请稍后再试！"];
        }
    }];
}


/**
 添加图片
 */
- (void)clickedAddImage
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    @weakify(self);
    // 拍照和视频
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.viewModel.photoType = 1;
        [self openPicOrVideoWithSign];
    }];
    UIAlertAction *pictureAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.viewModel.photoType = 0;
        [self openPicOrVideoWithSign];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:videoAction];
    [alertController addAction:pictureAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)openPicOrVideoWithSign
{
    UIImagePickerController *imagePicker = nil;
    if (self.viewModel.photoType == 0)
    {
        @weakify(self);
        //相册权限
//        [AuthorityManager getPhotoAuthorityWithAgreeAuthority:^(BOOL isAuthorized) {
//            @strongify(self);
//            if (isAuthorized)
//            {
//                
//            }
//        }];
        
        
        //本地相簿
        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: @"public.image", nil];
        imagePicker.delegate = self;
    }
    else
    {
        //相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: @"public.image", nil];
            imagePicker.delegate = self;
        }
    }
    if (imagePicker)
    {
        if (@available(iOS 11.0, *))
        {
            [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentAutomatic];
        }
        [TYZJumpVCManager presentBaseVC:self presentVC:imagePicker completion:nil];
    }
}

#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (@available(iOS 11.0, *))
    {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])
    {
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        CGSize imgSize = image.size;
        
        if (imgSize.width > 200)
        {
            image = [UIImage imageWithImage:image scaledToSize:CGSizeMake(200, 200)];
        }
        
        NSData *imgData = UIImageJPEGRepresentation(image, 0.8);
        UIImage *upImage = [[UIImage alloc] initWithData:imgData];
        [self actionWithUploadImage: upImage];
//        self.viewModel.addImageModel.image = upImage;
//        [self.remarkImageView updateWithSignImage:self.viewModel.addImageModel];
//        self.viewModel.base64 = [imgData base64EncodedString];
//        [self requestModifyPhoto];// 提交
//        [self.uploadImageView loadImage:image fileId:@""];
//        [self.uploadArr addObject:image];
//        _rootView.contentSize = CGSizeMake(self.rootView.width, self.uploadImageView.bottom + 10);
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (@available(iOS 11.0, *))
    {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}

/// 单击
/// - Parameter model: model description
- (void)actionWithCell:(TYZCommonCellModel *)model {
    if ([objectNull(model.title) isEqualToString:@"用户生日"]) {
        [self.datePicker show];
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TYZCommonCellModel *model = [self.viewModel.dataList objectOrNilAtIndex:indexPath.row];
    if ([model.title isEqualToString:@"所属服务站"] || [model.title isEqualToString:@"所属角色"]) {
        return model.cellHeight;
    }
//    if (indexPath.row == 0) { // 头像
//        return kWDPersonalSettingHeaderCellHeight;
//    } else {
        return kWDPersonalSettingViewCellHeight;
//    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TYZCommonCellModel *model = [self.viewModel.dataList objectOrNilAtIndex:indexPath.row];
    @weakify(self);
    if ([model.title isEqualToString:@"所属服务站"] || [model.title isEqualToString:@"所属角色"]) {
        WDPersonalSettingNewViewCell *cell = [WDPersonalSettingNewViewCell cellForTableView:tableView indexPath:indexPath];
        cell.contentView.size = CGSizeMake(kScreenW, model.cellHeight);
        [cell updateCellData:model];
        return cell;
    }
//    if (indexPath.row == 0) { // 头像
//        WDPersonalSettingHeaderCell *cell = [WDPersonalSettingHeaderCell cellForTableView:tableView indexPath:indexPath];
//        [cell updateCellData:model];
//        cell.touchHeaderBlock = ^{
//            @strongify(self);
//            [self actionWithUpdateHeaderImage];
//        };
//        [cell updateCellData:model];
//        return cell;
//    } else {
        WDPersonalSettingViewCell *cell = [WDPersonalSettingViewCell cellForTableView:tableView indexPath:indexPath];
        [cell updateCellData:model];
        
        cell.baseTableViewCellBlock = ^(id data) {
            @strongify(self);
            [self actionWithCell: data];
        };
        
        return cell;
//    }
}

@end
